package fun.stgoder.test1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class TestReadWriteLock {
    public static int n = 0;

    public static void main(String[] args) {
        ReadWriteLock lock = new ReentrantReadWriteLock();

        Lock readLock = lock.readLock();
        Lock writeLock = lock.writeLock();

        Runnable read = () -> {
            while (true) {
                readLock.lock();
                try {

                    System.out.println("read " + n);


                } finally {
                    readLock.unlock();
                }

                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Runnable write = () -> {
            while (true) {
                writeLock.lock();
                try {

                    System.out.println("write " + ++n);
                    TimeUnit.SECONDS.sleep(3);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    writeLock.unlock();
                }

                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        new Thread(read).start();
        new Thread(read).start();
        new Thread(read).start();
        new Thread(write).start();
    }
}
